package com.unlcn.ils.wms.backend.service.bigscreen.impl;

import cn.huiyunche.commons.exception.BusinessException;
import cn.huiyunche.commons.utils.HttpRequestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.unlcn.ils.wms.backend.bo.biBO.BiDRISTIONHEADBO;
import com.unlcn.ils.wms.backend.bo.biBO.BiDRISTIONLISTBO;
import com.unlcn.ils.wms.backend.dto.bigscreenDTO.DistributionChartDTO;
import com.unlcn.ils.wms.backend.enums.TmsUrlEnum;
import com.unlcn.ils.wms.backend.enums.TmsUrlTypeEnum;
import com.unlcn.ils.wms.backend.service.bigscreen.DistributionService;
import com.unlcn.ils.wms.backend.util.TimeUtil;
import com.unlcn.ils.wms.base.mapper.bigscreen.BiDistributionHeadMapper;
import com.unlcn.ils.wms.base.mapper.bigscreen.BiDistributionMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.BiDistributionExtMapper;
import com.unlcn.ils.wms.base.mapper.extmapper.BiDistributionHeadExtMapper;
import com.unlcn.ils.wms.base.mapper.outbound.WmsDepartureRegisterMapper;
import com.unlcn.ils.wms.base.mapper.sys.TmsCallHistoryMapper;
import com.unlcn.ils.wms.base.model.bigscreen.BiDistribution;
import com.unlcn.ils.wms.base.model.bigscreen.BiDistributionHead;
import com.unlcn.ils.wms.base.model.sys.TmsCallHistory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lenovo on 2017/11/13.
 */
@Service
public class DistributionServiceImpl implements DistributionService {

    @Autowired
    private BiDistributionHeadExtMapper biDistributionHeadExtMapper;

    @Autowired
    private BiDistributionExtMapper biDistributionExtMapper;

    @Autowired
    private BiDistributionHeadMapper biDistributionHeadMapper;

    @Autowired
    private BiDistributionMapper biDistributionMapper;

    @Autowired
    private TmsCallHistoryMapper tmsCallHistoryMapper;

    @Value("${tms.pickup.host.url}")
    private String propertyUrl;

    @Value("${tms.pickup.host.timeout}")
    private String propertyTime;

    @Value("${tms.encode.key}")
    private String propertyKey;

    private Logger LOGGER = LoggerFactory.getLogger(DistributionServiceImpl.class);

    @Override
    public List<DistributionChartDTO> distributionChartCount() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        // 查询五天内最新的提车推移图统计数据
        List<BiDistributionHead> biInOutDrayHeadList = biDistributionHeadExtMapper.distributionChartCount();

        DistributionChartDTO distributionChartDTO1 = new DistributionChartDTO();
        DistributionChartDTO distributionChartDTO2 = new DistributionChartDTO();
        DistributionChartDTO distributionChartDTO3 = new DistributionChartDTO();
        DistributionChartDTO distributionChartDTO4 = new DistributionChartDTO();

        distributionChartDTO1.setName("发运数");
        distributionChartDTO2.setName("在途数");
        distributionChartDTO3.setName("运抵数");
        distributionChartDTO4.setName("配送及时率");

        Integer[] count1 = new Integer[5];
        Integer[] count2 = new Integer[5];
        Integer[] count3 = new Integer[5];
        Float[] rate1 = new Float[5];

        String[] dates = TimeUtil.getBeforeDates1(5);
        for (int i = 0; dates.length > i; i++) {
            String date = dates[i];
            for (int num = 0; biInOutDrayHeadList.size() > num; num++) {
                BiDistributionHead biDistributionHead = biInOutDrayHeadList.get(num);
                if (format.format(biDistributionHead.getShippingTime()).contains(date)) {
                    count1[i] = biDistributionHead.getNumberHair();
                    count2[i] = biDistributionHead.getNumberPasses();
                    count3[i] = biDistributionHead.getNumberShip();
                    rate1[i] = biDistributionHead.getShipRate();
                    break;
                }
            }
        }
        for (Integer num = 0; count1.length > num; num++) {
            Integer count = count1[num];
            if (count == null)
                count1[num] = 0;
        }
        for (Integer num = 0; count2.length > num; num++) {
            Integer count = count2[num];
            if (count == null)
                count2[num] = 0;
        }
        for (Integer num = 0; count3.length > num; num++) {
            Integer count = count3[num];
            if (count == null)
                count3[num] = 0;
        }
        for (Integer num = 0; rate1.length > num; num++) {
            Float rate = rate1[num];
            if (rate == null)
                rate1[num] = new Float(0.0);
        }

        distributionChartDTO1.setData(count1);
        distributionChartDTO2.setData(count2);
        distributionChartDTO3.setData(count3);
        distributionChartDTO4.setRate(rate1);

        distributionChartDTO1.setDate(TimeUtil.getBeforeDates2(5));
        distributionChartDTO2.setDate(TimeUtil.getBeforeDates2(5));
        distributionChartDTO3.setDate(TimeUtil.getBeforeDates2(5));
        distributionChartDTO4.setDate(TimeUtil.getBeforeDates2(5));

        List<DistributionChartDTO> outDrayChartDataDTOList = new ArrayList<DistributionChartDTO>();
        outDrayChartDataDTOList.add(distributionChartDTO1);
        outDrayChartDataDTOList.add(distributionChartDTO2);
        outDrayChartDataDTOList.add(distributionChartDTO3);
        outDrayChartDataDTOList.add(distributionChartDTO4);

        return outDrayChartDataDTOList;
    }

    @Override
    public List<BiDistribution> distributionLineCount() {
        return biDistributionExtMapper.distributionLineCount();
    }

    /**
     * 获取配送的列表  12/23 增加板车实际进出场的时间
     *
     * @return
     */
    @Autowired
    private WmsDepartureRegisterMapper wmsDepartureRegisterMapper;

    @Override
    public List<BiDistribution> getDisLineAndGateTime() {
        LOGGER.info("DistributionServiceImpl.getDisLineAndGateTime param");
        return biDistributionExtMapper.distributionLineCount();
    }

    /**
     * 配送统计图
     */
    public void addDistributionChart() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String dateStr = format.format(calendar.getTime());

        String strUrl = propertyUrl + TmsUrlEnum.BI_DISTRIBUTIONCHART.getText();
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);

        map.put("date", dateStr);

        String result = null;

        TmsCallHistory tmsCallHistory = new TmsCallHistory();

        try {

            tmsCallHistory.setTmsUrl(strUrl);
            tmsCallHistory.setPullOrPush(0);
            tmsCallHistory.setCallStartTime(new Date());
            tmsCallHistory.setTmsUrlType(TmsUrlTypeEnum.BI_DISTRIBUTIONCHART.getValue());
            tmsCallHistory.setParameters(dateStr);
            result = HttpRequestUtil.sendHttpPost(strUrl, headerMap, map, time);

        } catch (Exception e) {
            LOGGER.error("DistributionServiceImpl.addDistributionChart error : ", e);
            throw new BusinessException("访问tms接口失败");
        }

        try {
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");

                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);

                if (!success) {
                    LOGGER.error("DistributionServiceImpl callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }

                List<BiDRISTIONHEADBO> tmsBOList = JSONArray.parseArray(records, BiDRISTIONHEADBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());

                tmsBOList.forEach((BiDRISTIONHEADBO v) -> {
                    //新增
                    BiDistributionHead biDistributionHead = new BiDistributionHead();
                    biDistributionHead.setVersion(dateStr2);

                    biDistributionHead.setNumberHair(Integer.parseInt(Strings.isNullOrEmpty(v.getOut_qty()) ? "0" : v.getOut_qty()));
                    biDistributionHead.setNumberPasses(Integer.parseInt(Strings.isNullOrEmpty(v.getOnway_qty()) ? "0" : v.getOnway_qty()));
                    biDistributionHead.setNumberShip(Integer.parseInt(Strings.isNullOrEmpty(v.getArrival_qty()) ? "0" : v.getArrival_qty()));
                    biDistributionHead.setShipRate(Float.parseFloat(Strings.isNullOrEmpty(v.getIntime_radio()) ? "0" : v.getIntime_radio()));

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

                    try {
                        biDistributionHead.setShippingTime(sdf.parse(v.getRpt_date()));
                    } catch (ParseException e) {
                        LOGGER.error("DistributionServiceImpl.addDistributionChart error : ", e);
                        throw new BusinessException("日期转换异常!");
                    }

                    biDistributionHeadMapper.insertSelective(biDistributionHead);

                });
            }

        } catch (Exception e) {
            LOGGER.error("DistributionServiceImpl.addDistributionChart error : ", e);
            throw new BusinessException("保存失败");
        }
    }

    /**
     * 配送统计列表
     */
    public void addDistributionLine() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        String dateStr = format.format(calendar.getTime());

        String strUrl = propertyUrl + TmsUrlEnum.BI_DISTRIBUTIONLINE.getText();
        Integer time = Integer.parseInt(propertyTime);
        String encode_key = propertyKey;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("encode-key", encode_key);
        map.put("date", dateStr);

        String result = null;

        TmsCallHistory tmsCallHistory = new TmsCallHistory();

        try {

            tmsCallHistory.setTmsUrl(strUrl);
            tmsCallHistory.setPullOrPush(0);
            tmsCallHistory.setCallStartTime(new Date());
            tmsCallHistory.setTmsUrlType(TmsUrlTypeEnum.BI_DISTRIBUTIONLINE.getValue());
            tmsCallHistory.setParameters(dateStr);
            result = HttpRequestUtil.sendHttpPost(strUrl, headerMap, map, time);

        } catch (Exception e) {
            LOGGER.error("DistributionServiceImpl.addDistributionLine error : ", e);
            throw new BusinessException("访问tms接口失败");
        }

        try {
            if (StringUtils.isNotBlank(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                String msg = jsonObject.getString("message");
                String records = jsonObject.getString("records");
                Boolean success = jsonObject.getBoolean("success");

                tmsCallHistory.setCallEndTime(new Date());
                tmsCallHistory.setMessage(msg);
                tmsCallHistory.setResultContent(result);

                if (!success) {
                    LOGGER.error("addDistributionLine callTms error msg: {}", msg);
                    tmsCallHistory.setResultCount(0);
                    tmsCallHistory.setSuccess(success);
                    tmsCallHistoryMapper.insertSelective(tmsCallHistory);
                }

                List<BiDRISTIONLISTBO> tmsBOList = JSONArray.parseArray(records, BiDRISTIONLISTBO.class);
                tmsCallHistory.setResultCount(tmsBOList.size());
                tmsCallHistory.setSuccess(success);
                tmsCallHistoryMapper.insertSelective(tmsCallHistory);

                SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmSS");
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(new Date());
                String dateStr2 = format2.format(calendar2.getTime());


                tmsBOList.forEach((BiDRISTIONLISTBO v) -> {
                    //新增
                    BiDistribution biDistribution = new BiDistribution();

                    biDistribution.setDispatchNo(v.getShipno());
                    biDistribution.setVehicleCard(v.getVehicle());
                    biDistribution.setCarrierName(v.getSupplier());
                    biDistribution.setDirverName(v.getDriver());
                    biDistribution.setPhone(v.getMobile());
                    biDistribution.setStatus(v.getStatus());
                    biDistribution.setVersion(dateStr2);

                    //bugfix  2018-1-3  修复配送页面的计划抵达时间为零点
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HHmm");

                    try {
                        biDistribution.setPlanArriveTime(sdf.parse(v.getEst_arrival_date()));
                    } catch (ParseException e) {
                        LOGGER.error("DistributionServiceImpl.addDistributionLine error : ", e);
                        throw new BusinessException("日期转换异常!");
                    }
                    biDistributionMapper.insertSelective(biDistribution);
                });
            }

        } catch (Exception e) {
            LOGGER.error("DistributionServiceImpl.addDistributionLine error : ", e);
            throw new BusinessException("保存失败");
        }
    }
}
